﻿using System;
using Autofac;
using System.Windows.Forms;
using ComputerVision.BaseForm;
using ComputerVision.Common;
using ComputerVision.Data;
using ComputerVision.Services;
using QuanLyThongTinCoSo.Common;

namespace ComputerVision.QuanHuyenForm
{
    public partial class frmQuanHuyenList : frmList
    {
        private IService<QuanHuyen> _quanHuyenService;
        public frmQuanHuyenList()
        {
            InitializeComponent();
            _quanHuyenService = Program.Container.Resolve<IService<QuanHuyen>>();
        }

        protected override void LoadData()
        {
            _quanHuyenService = Program.Container.Resolve<IService<QuanHuyen>>();
            quanHuyenBindingSource.DataSource = _quanHuyenService.ToList();
        }

        protected override void Add()
        {
            using (var frm = new frmQuanHuyenDetail())
            {
                frm.OnLoadData += LoadData;
                frm.ShowDialog();
            }
        }

        protected override void Edit()
        {
            EditData();
        }

        private void EditData()
        {
            if (dgvQuanHuyen.SelectedRows.Count > 0)
            {
                var selectedRow = dgvQuanHuyen.SelectedRows[0];
                var id = Guid.Parse(selectedRow.Cells[0].Value.ToString());
                using (var fEdit = new frmQuanHuyenDetail(id))
                {
                    fEdit.OnLoadData += LoadData;
                    fEdit.ShowDialog();
                }
            }
            else
            {
                AlertList.Error("Lỗi trong quá trình sửa dữ liệu");
            }
        }

        private void DeleteData()
        {
            try
            {
                if (dgvQuanHuyen.SelectedRows.Count != 0)
                {
                    var id = Guid.Parse(dgvQuanHuyen.SelectedRows[0].Cells[0].Value.ToString());
                    if (DialogResult.Yes == AlertList.Question(Constants.Messages.DeleteConfirm))
                    {
                        var item = _quanHuyenService.Detail(id);
                        _quanHuyenService.Delete(item);
                        LoadData();
                    }
                }
                else
                {
                    AlertList.Error(Constants.Messages.UpdateSelectItemError);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        protected override void Delete()
        {
            DeleteData();
        }
    }
}
